package com.styles.codingstyle.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Package com.styles.codingstyle.aspect
 * @Description: 统一请求日志记录处理
 * @Author 陈建
 * @Create: 2018-05-29 10:40
 * @Version 1.0
 * @Update: message
 */
@Aspect
@Component
public class HttpAspect {

    private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);

    /**
     * @Description: 请求日志
     * @Param: []
     * @Return: void
     * @Author: 陈建
     * @date: 2018/5/29 10:57
     */
    @Pointcut("execution(public * com.styles.codingstyle.controller.*.*(..))")
    public void log() {
    }

    /**
     * @Description: 前置
     * @Param: []
     * @Return: void
     * @Author: 陈建
     * @date: 2018/5/29 10:57
     */
    @Before("log()")
    public void doHttpBeforeLog(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //记录请求信息(使用时候取消注释)
        // logger.info("RequestTime={} IP={} Method={} Url={} Args={} Class_Method={}", System.currentTimeMillis(), request.getRemoteAddr(), request.getMethod(), request.getRequestURL(), joinPoint.getArgs(), joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
    }

    /**
     * @Description: 相应记录, 在正常返回后记录数据
     * @Param: [object]
     * @Return: void
     * @Author: 陈建
     * @date: 2018/6/12 13:44
     */
    @AfterReturning(returning = "object", pointcut = "log()")
    public void doHttpAterReturning(Object object) {
        //防止object为null,调用tostring方法时空指针;
        if (StringUtils.isEmpty(object)) {
            // logger.info("ResponseTime={} Response={}", System.currentTimeMillis(), "Return object is empty!");
        } else {
            //logger.info("ResponseTime={} Response={}", System.currentTimeMillis(), object.toString());
        }
    }
}
